<template>
  <el-table :data="borrowBook" style="width: 100%">
    <el-table-column prop="isbn" label="ISBN" width="140"></el-table-column>
    <el-table-column prop="bookId" label="bookId" width="140"></el-table-column>
    <el-table-column
      prop="borrowDate"
      label="borrow Date"
      width="180"
      :formatter="dateFormatter"
    ></el-table-column>
    <el-table-column
      prop="returnDate"
      label="return Date"
      width="180"
      :formatter="dateFormatter"
    ></el-table-column>
    <el-table-column
      prop="lastDay"
      label="remain Days"
      width="120"
    ></el-table-column>
    <el-table-column
      prop="fine"
      label="arrearage(yuan)"
      width="150"
      :formatter="arrearageFormatter"
    ></el-table-column>
    <el-table-column label="renew book" width="120">
      <template v-slot="scope">
        <el-button type="primary" value="return" @click="renewBook(scope.row)"
          >renew</el-button
        >
      </template>
    </el-table-column>
    <el-table-column label="pay for money">
      <template v-slot="scope">
        <el-button type="primary" @click="payMoney(scope.row)"
          >pay</el-button
        >
      </template>
    </el-table-column>
  </el-table>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import * as bookApi from "@/api/books";
import { ElMessage } from "element-plus";
import type { BorrowBook } from "@/domain/book";

const borrowBook = ref<BorrowBook[]>([]);
const getBorrowBook = () => {
  bookApi.getBorrowBooks().then((data) => {
    borrowBook.value = data;
    console.log('data', data);

  });
};
const dateFormatter = (row: any, col: any, value: string | number | Date) => {
  return `${new Date(value).toLocaleDateString()} ${new Date(value).toLocaleTimeString()}`;
};
const arrearageFormatter = (row: any, col: any, value: string | number) => {
  return (Number(value) === 0) ? 'no arrearage' : value;
};

const renewBook = (params: { readerId: number; isbn: string }) => {
  bookApi.renewBook({ userId: params.readerId, isbn: params.isbn }).then(() => {
    ElMessage.success("renew success");
    setTimeout(() => getBorrowBook(), 1000);
  })
  .catch(err => {
    ElMessage.error(err);
  });
};
const payMoney = (params: { bookId: string }) => {
  location.href = `http://localhost:8080/barcode/index.html?bookId=${params.bookId}`
};
onMounted(() => {
  getBorrowBook();
});
</script>

<style scoped></style>
